package com.vf.admin.client.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.controller.pay.nopay.service.AppNoPayService;
import com.vf.admin.client.dao.AppOrderDao;
import com.vf.admin.client.dao.AlipayConfigsDao;
import com.vf.admin.client.enums.PayTypeEnum;
import com.vf.admin.client.result.PayInfoResult;
import com.vf.admin.client.service.AlipayConfigsService;
import com.vf.admin.client.service.AppOrderService;
import com.vf.admin.client.service.VipOrderService;
import com.vf.admin.client.service.pay.AppPaySetupLoadBalancer;
import com.vf.admin.common.BizException;
import com.vf.admin.common.Constants;
import com.vf.admin.fiwork.util.TimeUtil;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.utils.Md5Util1;
import com.vf.admin.utils.OkHttpClient;
import com.vf.admin.utils.TimeUtils;
import com.vf.admin.utils.pay.ApiAplayWeChat.IpUtils;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.PrivateKey;
import java.util.Date;
import java.util.List;
import java.util.Random;

import static com.vf.admin.utils.RandomUtil.getOrderIdByUUId;

/**
 * 系统配置
 */
@Service
public class AlipayConfigsServiceImpl implements AlipayConfigsService {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AlipayConfigsDao alipayConfigsDao;
    //钱包订单
    @Autowired
    private AppOrderService appOrderService;
    //vip订单
    @Autowired
    private VipOrderService vipOrderService;
    @Autowired
    private AppNoPayService appNoPayService;


    /**
     * 支付宝支付宝预下单   废弃
     *
     * @param user 充值用户
     * @return
     */
    @Override
    public String otherAlipayWeb(AppUser user, AppCzMoney czMoney) {
        //添加订单记录
        AppOrder appOrder = new AppOrder();
        appOrder.setCreatetime(new Date());
        appOrder.setOrdernum(getOrderIdByUUId());//生成订单号
        appOrder.setCzMoneyId(czMoney.getId());
        appOrder.setMoney(new BigDecimal(czMoney.getMoney()));
        appOrder.setStatus(Constants.dingdan_status_dfk);//默认 1、代付款 2、已付款
        appOrder.setType(Constants.dingdan_zhiFuLeiXing_zfb); //订单支付类型  默认 1、支付宝 2、微信 3、苹果
        appOrder.setUserid(user.getId());//下单人信息
        appOrder.setPic(user.getPic());
        appOrder.setNick(user.getNick());
        appOrder.setPhone(user.getLoginname());
        appOrder.setNum(czMoney.getDiamonds().add(czMoney.getGive()));
        appOrderService.save(appOrder);

        //***************** 支付宝预处理 **********************
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel(); //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式
        model.setBody("充值");//对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
        model.setSubject("钻石充值");//商品名称
        model.setOutTradeNo(appOrder.getOrdernum()); //商户订单号(自动生成)
//        model.setTotalAmount(new BigDecimal(czMoney.getMoney()).setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString());//支付金额
        model.setTotalAmount("0.01");
        model.setProductCode("QUICK_WAP_PAY");//销售产品码（固定值）

        //权重的方法
        AlipayConfigs randomConfig = getWeightPlayInfo();

        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeWapPayRequest webRequest = new AlipayTradeWapPayRequest();
        webRequest.setBizModel(model);
        webRequest.setNotifyUrl(randomConfig.getNotifyUrl() + "/" + randomConfig.getAppId());//异步回调地址（后台）  拼接appId
        webRequest.setReturnUrl(randomConfig.getReturnUrl());

        //返回支付宝订单信息(预处理)
        AlipayClient alipayClient = new DefaultAlipayClient(
                randomConfig.getGateWayUrl(),
                randomConfig.getAppId(),
                randomConfig.getAppPrivateKey(),
                randomConfig.getFormat(),
                randomConfig.getCharset(),
                randomConfig.getAlipayPublicKey(),
                randomConfig.getSignType()
        );

        String orderString = "";
        try {
            orderString = alipayClient.pageExecute(webRequest, "get").getBody();
        } catch (Exception e) {
            return orderString;
        }
        return orderString;
    }

    /**
     * 查找当前可用的支付信息
     * 通过权重来分配当前用那个支付。权重为概率值。总概率为100
     *
     * @return
     */
    public AlipayConfigs getWeightPlayInfo() {
        List<AlipayConfigs> alipayConfigs = alipayConfigsDao.list();;
//        if (!redisUtil.hasKey(RedisKeys.ALICONFIGS)) {
//            alipayConfigs = alipayConfigsDao.list();
//            redisUtil.set(RedisKeys.ALICONFIGS, alipayConfigs, RedisKeys.ALICONFIGSOUTTIME);
//        } else {
//            alipayConfigs = (List<AlipayConfigs>) redisUtil.get(RedisKeys.ALICONFIGS);
//        }
        Integer sumWeight = 0;//总权重的值
        JSONArray as = new JSONArray();//存入对象用于概率
        Integer index = 0;
        for (int i = 0; i < alipayConfigs.size(); i++) {
            Integer weight = alipayConfigs.get(i).getWeight();
            if (weight > 0) {
                sumWeight = sumWeight + weight;
                for (int j = 0; j < weight; j++) {
                    as.add(index, alipayConfigs.get(i));
                    index++;//放后面保证0也有值
                }
            }
        }
        Integer r = new Random().nextInt(sumWeight + 1);//随机数生成概率
        AlipayConfigs alipayConfigs1 = (AlipayConfigs) as.get(r);
        System.out.println("权重：" + alipayConfigs1);
        return (AlipayConfigs) as.get(r);
    }

    @Override
    public AlipayConfigs getAppIdInfo(String appIdStr) {
        return alipayConfigsDao.getAppIdInfo(appIdStr);
    }

    @Override
    public PayInfoResult aliPayDiamondTransactionsH5(AppUser user, AppCzMoney czMoney,String mobileSpec) {
        //权重的方法
        AlipayConfigs randomConfig = getWeightPlayInfo();
        //添加订单记录
        AppOrder appOrder = new AppOrder();
        appOrder.setCreatetime(new Date());
        appOrder.setOrdernum(getOrderIdByUUId());//生成订单号
        appOrder.setCzMoneyId(czMoney.getId());
        appOrder.setMoney(new BigDecimal(czMoney.getMoney()));
        appOrder.setStatus(Constants.dingdan_status_dfk);//默认 1、代付款 2、已付款
        appOrder.setType(Constants.dingdan_zhiFuLeiXing_zfb); //订单支付类型  默认 1、支付宝 2、微信 3、苹果  4、杉德支付宝 5、杉德微信
        appOrder.setUserid(user.getId());//下单人信息
        appOrder.setPic(user.getPic());
        appOrder.setNick(user.getNick());
        appOrder.setPhone(user.getLoginname());
        appOrder.setNum(czMoney.getDiamonds().add(czMoney.getGive()));
        appOrder.setMobileSpec(mobileSpec);
        appOrderService.save(appOrder);
        //***************** 支付宝预处理 **********************
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel(); //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式
        model.setBody("充值");//对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
        model.setSubject("钻石充值");//商品名称
        model.setOutTradeNo(appOrder.getOrdernum()); //商户订单号(自动生成)
        model.setTotalAmount(new BigDecimal(czMoney.getMoney()).setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString());//支付金额
//        model.setTotalAmount("0.01");
        model.setProductCode("QUICK_WAP_PAY");//销售产品码（固定值）
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeWapPayRequest webRequest = new AlipayTradeWapPayRequest();
        webRequest.setBizModel(model);
        webRequest.setNotifyUrl(randomConfig.getNotifyUrl() + "/" + randomConfig.getAppId());//异步回调地址（后台）  拼接appId
        webRequest.setReturnUrl(randomConfig.getReturnUrl());
        //返回支付宝订单信息(预处理)
        AlipayClient alipayClient = new DefaultAlipayClient(
                randomConfig.getGateWayUrl(),
                randomConfig.getAppId(),
                randomConfig.getAppPrivateKey(),
                randomConfig.getFormat(),
                randomConfig.getCharset(),
                randomConfig.getAlipayPublicKey(),
                randomConfig.getSignType()
        );
        PayInfoResult payInfoResult = new PayInfoResult();
        String orderString = "";
        try {
            orderString = alipayClient.pageExecute(webRequest, "get").getBody();
            payInfoResult.setOrderNo(appOrder.getOrdernum());
            payInfoResult.setPayUrl(orderString);
        } catch (Exception e) {
            return payInfoResult;
        }
        return payInfoResult;
    }

    @Override
    public PayInfoResult aliPayOpenVipTransactionsH5(AppUser user, VipPackage vipPackage,String mobileSpec) {
        //权重的方法
        AlipayConfigs randomConfig = getWeightPlayInfo();
        //添加订单记录
        VipOrder vipOrder = new VipOrder();
        vipOrder.setUserId(user.getId());
        vipOrder.setOrderNo(getOrderIdByUUId());//订单号
        vipOrder.setVipPackageId(vipPackage.getId());
        vipOrder.setStatus(0);  //0待支付 1已支付
        vipOrder.setPayType("alipay");
        vipOrder.setCreateTime(new Date());
        vipOrder.setType(Constants.dingdan_zhiFuLeiXing_zfb); //订单支付类型  默认 1、支付宝 2、微信 3、苹果  4、杉德支付宝 5、杉德微信
        vipOrder.setMobileSpec(mobileSpec);
        vipOrder.setNick(user.getNick());
        vipOrder.setPhone(user.getLoginname());
        vipOrder.setPrice(vipPackage.getPrice());
        vipOrder.setPic(user.getPic());
        vipOrderService.save(vipOrder);
        try {
            appNoPayService.addAlipayCount();
        }catch (Exception e){
        }
        //***************** 支付宝预处理 **********************
        String goodsName = "会员充值";
        if(ObjectUtil.equal(100, vipPackage.getId())){
            goodsName = "popose七天会员";
        }else if(ObjectUtil.equal(101, vipPackage.getId())){
            goodsName = "popose三月会员";
        }else if(ObjectUtil.equal(102, vipPackage.getId())){
            goodsName = "popose一年会员";
        }else if(ObjectUtil.equal(103, vipPackage.getId())){
            goodsName = "popose2年会员";
        }
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel(); //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式
        model.setBody(goodsName);//对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
        model.setSubject(goodsName);//商品名称
        model.setOutTradeNo(vipOrder.getOrderNo()); //商户订单号(自动生成)
        model.setTotalAmount(vipPackage.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString());//支付金额
        model.setProductCode("QUICK_WAP_PAY");//销售产品码（固定值）
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeWapPayRequest webRequest = new AlipayTradeWapPayRequest();
        webRequest.setBizModel(model);
        webRequest.setNotifyUrl(randomConfig.getVipNotifyUrl() + "/" + randomConfig.getAppId());//异步回调地址（后台）  拼接appId
        webRequest.setReturnUrl(randomConfig.getReturnUrl());
        //返回支付宝订单信息(预处理)
        AlipayClient alipayClient = new DefaultAlipayClient(
                randomConfig.getGateWayUrl(),
                randomConfig.getAppId(),
                randomConfig.getAppPrivateKey(),
                randomConfig.getFormat(),
                randomConfig.getCharset(),
                randomConfig.getAlipayPublicKey(),
                randomConfig.getSignType()
        );
        PayInfoResult payInfoResult = new PayInfoResult();
        String orderString = "";
        try {
            orderString = alipayClient.pageExecute(webRequest, "get").getBody();
            payInfoResult.setOrderNo(vipOrder.getOrderNo());
            payInfoResult.setPayUrl(orderString);
        } catch (Exception e) {
            return payInfoResult;
        }
        return payInfoResult;
    }

    /**
     * 永安
     */
    @Override
    public PayInfoResult aliPayOpenVipTransactionsH511(AppUser user, VipPackage vipPackage, String mobileSpec, PayTypeEnum payTypeEnum, PaySelect paySelect) {
        //添加订单记录
        VipOrder vipOrder = new VipOrder();
        vipOrder.setUserId(user.getId());
        vipOrder.setOrderNo(getOrderIdByUUId());//订单号
        vipOrder.setVipPackageId(vipPackage.getId());
        vipOrder.setStatus(0);  //0待支付 1已支付
        vipOrder.setPayType(payTypeEnum.getValue());
        vipOrder.setType(payTypeEnum.getType());
        vipOrder.setCreateTime(new Date());
        vipOrder.setMobileSpec(mobileSpec);
        vipOrder.setNick(user.getNick());
        vipOrder.setPhone(user.getLoginname());
        vipOrder.setPrice(vipPackage.getPrice());
        vipOrder.setPic(user.getPic());
        vipOrderService.save(vipOrder);

        StringBuffer httpArg = new StringBuffer();
        String sign;
        String channelCode = paySelect.getChannelCode();
        String secretKey = paySelect.getSecretKey();//商户秘钥
        String mchId = paySelect.getMchId();//商户号
        String notifyUrl = paySelect.getNotifyUrl();
        httpArg.append("channelCode=").append(channelCode).append("&");
        httpArg.append("merOrderTid=").append(vipOrder.getOrderNo()).append("&");
        httpArg.append("mid=").append(mchId).append("&");
        httpArg.append("money=").append(vipPackage.getPrice()).append("&");
        httpArg.append("notifyUrl=").append(notifyUrl);
//        System.out.println("参数:"+httpArg);
        sign = Md5Util1.md5Hex(httpArg + "&" +secretKey);
        System.out.println("sign:"+sign);
        httpArg.append("&");
        httpArg.append("sign=").append(sign);

        String httpUrl = "http://qzbf8y134dxd.itsfpy.com/api/services/app/Api_PayOrder/CreateOrderPay";

        PayInfoResult payInfoResult = new PayInfoResult();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(httpUrl);
            StringEntity params = new StringEntity(httpArg.toString());
//          StringEntity entity = new StringEntity(params, ContentType.APPLICATION_JSON);
            params.setContentType("text/plain");
            httpPost.setEntity(params);
            httpPost.setHeader("Accept", "application/json");
//            httpPost.setHeader("Content-type", "application/json");
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            String result = EntityUtils.toString(responseEntity, "UTF-8");
            System.out.println("result:"+result);

            JSONObject jsonObject = JSON.parseObject(result);
            Integer status = jsonObject.getInteger("status");
            if(ObjectUtil.equal(0, status)){
                JSONObject jsonObject2 = jsonObject.getJSONObject("result");
                String payUrl = jsonObject2.getString("payUrl");
                payInfoResult.setPayUrl(payUrl);
                if(ObjectUtil.equal("1003", paySelect.getChannelCode())){
                    payInfoResult.setScan(true);
                }
            }else{
                payInfoResult.setMessage(jsonObject.getString("errMsg"));
            }
//            {"status":1,"errMsg":"当前无可用通道","result":null}
        } catch (Exception e) {
            e.printStackTrace();
            payInfoResult.setMessage(e.getMessage());
        }

        return payInfoResult;
    }

    /**
     * 汇付天下
     */
    @Override
    public PayInfoResult aliPayOpenVipTransactionsH522(AppUser user, VipPackage vipPackage,String mobileSpec, PaySelect paySelect) {
        PayTypeEnum payTypeEnum = PayTypeEnum.ALIPAY_HFTX;
        //添加订单记录
        VipOrder vipOrder = new VipOrder();
        vipOrder.setUserId(user.getId());
        vipOrder.setOrderNo(getOrderIdByUUId());//订单号
        vipOrder.setVipPackageId(vipPackage.getId());//
        vipOrder.setStatus(0);  //0待支付 1已支付
        vipOrder.setPayType(payTypeEnum.getValue());
        vipOrder.setCreateTime(new Date());
        vipOrder.setType(payTypeEnum.getType()); //订单支付类型  默认 1、支付宝 2、微信 3、苹果  4、杉德支付宝 5、杉德微信
        vipOrder.setMobileSpec(mobileSpec);
        vipOrder.setNick(user.getNick());
        vipOrder.setPhone(user.getLoginname());
        vipOrder.setPrice(vipPackage.getPrice());
        vipOrder.setPic(user.getPic());
        vipOrderService.save(vipOrder);
        //金额
        int amount = vipPackage.getPrice().multiply(new BigDecimal(100)).intValue();//单位是分
        //获取ip地址
        //请求URL
        // 请求body参数
        String notify_url = paySelect.getNotifyUrl();
        long timestamp = System.currentTimeMillis()/1000;
        String clientId = paySelect.getMchId();
        String title = "会员充值";
        String detail = "会员充值";
        String payType = "alipay";
        StringBuffer sign = new StringBuffer();
        sign.append("amount=").append(amount).append("&");
        sign.append("detail=").append(detail).append("&");
        sign.append("merchant_order_no=").append(vipOrder.getOrderNo()).append("&");
        sign.append("notify_url=").append(notify_url).append("&");
        sign.append("pay_type=").append(payType).append("&");
        sign.append("timestamp=").append(timestamp).append("&");
        sign.append("title=").append(title).append("&");
        sign.append("secretKey=").append(paySelect.getSecretKey()).append("&");
        sign.append("clientId=").append(clientId);
//        System.out.println("sign:"+sign.toString());
        String signMd5 = Md5Util1.md5Hex(sign.toString());
        System.out.println("signMd5:"+signMd5.toString());
        String json = "{"
                + "\"client_id\": \"" + clientId + "\","
                + "\"sign\": \"" + signMd5 + "\","
                + "\"body\": {"
                + "\"amount\": \"" + amount + "\","
                + "\"detail\": \"" + detail + "\","
                + "\"merchant_order_no\": \"" + vipOrder.getOrderNo() + "\","
                + "\"notify_url\": \"" + notify_url + "\","
                + "\"pay_type\": \"" + payType + "\","
                + "\"timestamp\": " + timestamp + ","
                + "\"title\": \"" + title + "\""
                + "}"
                + "}";
        System.out.println("json:"+json);
        String result = OkHttpClient.doPost("http://xcpay.top/api/Order/createOrder", json);
        System.out.println(result);

        PayInfoResult payInfoResult = new PayInfoResult();
        JSONObject jsonObject = JSON.parseObject(result);
        JSONObject jsonObject2 = jsonObject.getJSONObject("data");
        JSONObject jsonObject3 = jsonObject2.getJSONObject("pay_info");
        String payUrl = jsonObject3.getString("url");
        payInfoResult.setPayUrl(payUrl);
        return payInfoResult;
    }

    /**
     * 支付宝16
     */
    @Override
    public PayInfoResult aliPayOpenVipTransactionsH533(AppUser user, VipPackage vipPackage, String mobileSpec, PaySelect paySelect){
        PayTypeEnum payTypeEnum = PayTypeEnum.ALIPAY_XZZB;
        //添加订单记录
        VipOrder vipOrder = new VipOrder();
        vipOrder.setUserId(user.getId());
        vipOrder.setOrderNo(getOrderIdByUUId());//订单号
        vipOrder.setVipPackageId(vipPackage.getId());
        vipOrder.setStatus(0);  //0待支付 1已支付
        vipOrder.setPayType(payTypeEnum.getValue());
        vipOrder.setType(payTypeEnum.getType());
        vipOrder.setCreateTime(new Date());
        vipOrder.setMobileSpec(mobileSpec);
        vipOrder.setNick(user.getNick());
        vipOrder.setPhone(user.getLoginname());
        vipOrder.setPrice(vipPackage.getPrice());
        vipOrder.setPic(user.getPic());
        vipOrderService.save(vipOrder);

        int amount = vipPackage.getPrice().multiply(new BigDecimal(100)).intValue();//单位是分
        StringBuffer httpArg = new StringBuffer();
        String sign;
        String secretKey = paySelect.getSecretKey();//商户秘钥
        String mchId = paySelect.getMchId();//商户号
        String productId = paySelect.getProductId();//产品id
        httpArg.append("amount=").append(amount).append("&");
        httpArg.append("mchId=").append(mchId).append("&");
        httpArg.append("mchOrderNo=").append(vipOrder.getOrderNo()).append("&");
        httpArg.append("notifyUrl=").append(paySelect.getNotifyUrl()).append("&");
        httpArg.append("productId=").append(productId);
        System.out.println("sign参数:"+httpArg);
        sign = Md5Util1.md5Hex(httpArg + "&key=" + secretKey);
        System.out.println("sign:"+sign);
        httpArg.append("&");
        httpArg.append("sign=").append(sign);

        String httpUrl = "http://pay.yumif.cfd/api/pay/create_order";
        httpUrl += "?" + httpArg;
        System.out.println("httpUrl:"+httpUrl);

        PayInfoResult payInfoResult = new PayInfoResult();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(httpUrl);
            StringEntity params = new StringEntity(httpArg.toString());
            httpPost.setEntity(params);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            String result = EntityUtils.toString(responseEntity, "UTF-8");
            System.out.println("result:"+result);

            JSONObject jsonObject = JSON.parseObject(result);
            JSONObject jsonObject2 = jsonObject.getJSONObject("payParams");
            String payUrl = jsonObject2.getString("payUrl");
            payInfoResult.setPayUrl(payUrl);

//            {"errCode":"0121","errDes":"支持最小支付金额:10到最大金额:500","retCode":"FAIL","retMsg":"org.xxpay.core.common.domain.AvailablePassageVO@1dd9d7fe"}
        } catch (Exception e) {
            e.printStackTrace();
        }
        return payInfoResult;
    }

    /**
     * 奈斯
     */
    @Override
    public PayInfoResult aliPayOpenVipTransactionsH544(AppUser user, VipPackage vipPackage, String mobileSpec, PaySelect paySelect){
        PayTypeEnum payTypeEnum = PayTypeEnum.ALIPAY_NS;
        //添加订单记录
        VipOrder vipOrder = new VipOrder();
        vipOrder.setUserId(user.getId());
        vipOrder.setOrderNo(getOrderIdByUUId());//订单号
        vipOrder.setVipPackageId(vipPackage.getId());
        vipOrder.setStatus(0);  //0待支付 1已支付
        vipOrder.setPayType(payTypeEnum.getValue());
        vipOrder.setType(payTypeEnum.getType());
        vipOrder.setCreateTime(new Date());
        vipOrder.setMobileSpec(mobileSpec);
        vipOrder.setNick(user.getNick());
        vipOrder.setPhone(user.getLoginname());
        vipOrder.setPrice(vipPackage.getPrice());
        vipOrder.setPic(user.getPic());
        vipOrderService.save(vipOrder);

//        int amount = vipPackage.getPrice().multiply(new BigDecimal(100)).intValue();//单位是分
        StringBuffer httpArg = new StringBuffer();
        String sign;
        String secretKey = paySelect.getSecretKey();//商户秘钥
        String mchId = paySelect.getMchId();//商户号
        httpArg.append("pay_amount=").append(vipPackage.getPrice()).append("&");
        httpArg.append("pay_applydate=").append(TimeUtils.getNow()).append("&");
        httpArg.append("pay_bankcode=").append("1000").append("&");
        httpArg.append("pay_callbackurl=").append("http://api.ptszyxx.com").append("&");
        httpArg.append("pay_memberid=").append(mchId).append("&");
        httpArg.append("pay_notifyurl=").append(paySelect.getNotifyUrl()).append("&");
        httpArg.append("pay_orderid=").append(vipOrder.getOrderNo()).append("&");

        System.out.println("sign参数:"+httpArg + "key=" + secretKey);
        sign = Md5Util1.md5Hex(httpArg + "key=" + secretKey);
        System.out.println("sign:"+sign.toUpperCase());
        httpArg.append("pay_productname=").append("会员充值").append("&");
        httpArg.append("data_type=json").append("&");
        httpArg.append("pay_md5sign=").append(sign.toUpperCase());


        String httpUrl = "https://nicepays.cc/Pay_Index.html";

        PayInfoResult payInfoResult = new PayInfoResult();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(httpUrl);
            System.out.println("参数:"+httpArg.toString());
            StringEntity params = new StringEntity(httpArg.toString());
            httpPost.setEntity(params);
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.setHeader("charset", "UTF-8");
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            String result = EntityUtils.toString(responseEntity, "UTF-8");
            System.out.println("result:"+result);

            JSONObject jsonObject = JSON.parseObject(result);
            JSONObject jsonObject2 = jsonObject.getJSONObject("data");
            String payUrl = jsonObject2.getString("payurl");
            payInfoResult.setPayUrl(payUrl);
//            {"errCode":"0121","errDes":"支持最小支付金额:10到最大金额:500","retCode":"FAIL","retMsg":"org.xxpay.core.common.domain.AvailablePassageVO@1dd9d7fe"}
        } catch (Exception e) {
            e.printStackTrace();
        }
        return payInfoResult;
    }

    @Override
    public PayInfoResult shopH5(String name,BigDecimal price) {
        //权重的方法
        AlipayConfigs randomConfig = getWeightPlayInfo();
        //添加订单记录
        //***************** 支付宝预处理 **********************
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel(); //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式
        model.setBody("开通贵族");//对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
        model.setSubject("会员充值");//商品名称
        model.setOutTradeNo(getOrderIdByUUId()); //商户订单号(自动生成)
        model.setTotalAmount(price.setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString());//支付金额
//        model.setTotalAmount("0.01");
        model.setProductCode("QUICK_WAP_PAY");//销售产品码（固定值）
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeWapPayRequest webRequest = new AlipayTradeWapPayRequest();
        webRequest.setBizModel(model);
        webRequest.setNotifyUrl(randomConfig.getVipNotifyUrl() + "/" + randomConfig.getAppId());//异步回调地址（后台）  拼接appId
        webRequest.setReturnUrl(randomConfig.getReturnUrl());
        //返回支付宝订单信息(预处理)
        AlipayClient alipayClient = new DefaultAlipayClient(
                randomConfig.getGateWayUrl(),
                randomConfig.getAppId(),
                randomConfig.getAppPrivateKey(),
                randomConfig.getFormat(),
                randomConfig.getCharset(),
                randomConfig.getAlipayPublicKey(),
                randomConfig.getSignType()
        );
        PayInfoResult payInfoResult = new PayInfoResult();
        String orderString = "";
        try {
            orderString = alipayClient.pageExecute(webRequest, "get").getBody();
            payInfoResult.setOrderNo(model.getOutTradeNo());
            payInfoResult.setPayUrl(orderString);
        } catch (Exception e) {
            return payInfoResult;
        }
        return payInfoResult;
    }

    @Override
    public List<AlipayConfigs> list() {
        return alipayConfigsDao.list();
    }

    @Override
    public void openAlipayH5(String id) {
        alipayConfigsDao.openAlipayH5(id);
    }

}
